/*
 * download.c
 *
 *  Created on: Feb 5, 2012
 *      Author: daniel
 */

#include <stdbool.h>
#include <glib.h>
#include "download.h"
#include "SDL.h"
#include "SDL_ttf.h"

static GHashTable* downloads;

static SDL_Color textcolour;

static SDL_Surface* currentsurface;
static fonts_t* currentfonts;
static double currentdelta;
static int x = 0;
static unsigned elapsed = 0;

static bool havedownloads;

static fonts_t* fonts;

static void create(fonts_t* f) {
	memset(&textcolour, 0, sizeof(textcolour));
	downloads = g_hash_table_new(g_str_hash, g_str_equal);
	fonts = f;
}

static void render_download(gpointer key, gpointer value, gpointer user_data) {
	char text[256];

	job_t* j = value;

	char* format;

	if (strlen(j->name) > 15) {
		format = "%.12s... [%.2fmb]";
	}
	else {
		format = "%s [%.2fmb]";
	}

	snprintf(text, sizeof(text), format, j->name, j->mbleft);

	SDL_Surface* textsurface = TTF_RenderText_Blended(currentfonts->large, text, textcolour);

	if (textsurface != NULL ) {

		SDL_Rect dest;
		dest.y = (RENDERER_HEIGHT - textsurface->h) / 2;
		dest.x = x;

		SDL_BlitSurface(textsurface, NULL, currentsurface, &dest);

		SDL_FreeSurface(textsurface);
		x += textsurface->w + 10;
	}

}

static void render(SDL_Surface* surface, unsigned delta) {

	elapsed += delta;
	x = 0;
	currentsurface = surface;
	currentfonts = fonts;
	currentdelta = delta;

	SDL_FillRect(surface, NULL, 0xF00F);
	g_hash_table_foreach(downloads, render_download, NULL );

}

job_t* download_job_create(char* id, char* name) {
	job_t* j = malloc(sizeof(job_t));

	j->id = malloc(strlen(id) + 1);
	strcpy(j->id, id);

	j->name = malloc(strlen(name) + 1);
	strcpy(j->name, name);

	return j;
}

void download_job_destroyvalue(gpointer data) {
	job_t* j = data;
	free(j->id);
	free(j->name);
	free(j);
}

void download_add(job_t* j) {
	g_hash_table_insert(downloads, j->id, j);
	havedownloads = true;
}

void download_del(job_t* j) {
	g_hash_table_steal(downloads, j->id);
	havedownloads = g_hash_table_size(downloads) > 0;
}

static bool needstorender() {
	return havedownloads;
}

static bool shouldrender() {
	return havedownloads;
}

const renderer_t downloadrenderer = { "download", //
		create, //
		NULL, //
		shouldrender, //
		needstorender, //
		render, //
		NULL };
